package com.kakarota.hadoop.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 *   该程序放到hadoop里面运行的命令
 *   .\hadoop jar F:/hadoop/hadoop-0.0.1-SNAPSHOT.jar com.kakarota.hadoop.mapreduce.WordCountApp /hdfsapi/test/partitioner.txt /output/wc
 *
 * @program: hadoop-train
 * @description: 使用MapReduce开发WordCount应用程序
 * @author: 01
 * @create: 2018-03-31 14:03
 **/
public class WordCountApp {

    /**
     * Map: 读取输入的文件内容
     */
    public static class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable> {

        LongWritable one = new LongWritable(1);

        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            // 接收到的每一行数据
            String line = value.toString();

            // 按照指定的分割符进行拆分
            String[] words = line.split(" ");
//            for (String word : words) {
//                // 通过上下文把map的处理结果输出
//                context.write(new Text((word)), one);
//            }

//            // 通过上下文把map的处理结果输出
//            String wordName = "";
//            for (int cnt = 0; cnt < words.length - 2; cnt++) {
//                wordName = wordName + " " + words[cnt];
//            }
//            context.write(new Text((wordName)), new LongWritable(Long.parseLong(words[words.length - 1])));

            // 通过上下文把map的处理结果输出
            context.write(new Text((words[0])), new LongWritable(Long.parseLong(words[1])));

        }
    }

    /**
     * Partitioner: 设定Map Task输出的数据的分发规则
     */
    public static class MyPartitioner extends Partitioner<Text, LongWritable> {

        public int getPartition(Text key, LongWritable value, int numPartitions) {
            if(key.toString().equals("xiaomi")){
                return 0;
            }
            if(key.toString().equals("huawei")){
                return 1;
            }
            if(key.toString().equals("iphone7")) {
                return 2;
            }
            return 3;
        }
    }

    /**
     * Reduce: 归并操作
     */
    public static class MyReducer extends Reducer<Text, LongWritable, Text, LongWritable> {

        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0;
            for (LongWritable value : values) {
                // 求key出现的次数总和
                sum += value.get();
            }
            // 将最终的统计结果输出
            context.write(key, new LongWritable(sum));
        }
    }

    /**
     * 定义Driver：封装了MapReduce作业的所有信息
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        System.setProperty("HADOOP_HOME", "\\\\DESKTOP-I92VUSS\\f\\hadoop\\hadoop-3.3.5");

        Configuration configuration = new Configuration();

        // 准备清理已存在的输出目录
        Path outputPath = new Path(args[1]);
        FileSystem fileSystem = FileSystem.get(configuration);
        if (fileSystem.exists(outputPath)) {
            fileSystem.delete(outputPath,true);
            System.out.println("output file exists, but is has deleted");
        }

        // 创建Job，通过参数设置Job的名称
        Job job = Job.getInstance(configuration, "wordcount");

        // 设置Job的处理类
        job.setJarByClass(WordCountApp.class);

        // 设置作业处理的输入路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));

        // 设置map相关参数
        job.setMapperClass(MyMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        // 通过Job对象来设置Combiner处理类，在逻辑上和reduce是一样的
        /**
         * Combiner的适用场景：
         *
         * 求和、计数，累计类型的场景适合使用
         * Combiner的不适用的场景：
         *
         * 求平均数、求公约数等类型的操作不适合，如果这种场景下使用Combiner，得到的结果就是错误的
         */
        job.setCombinerClass(MyReducer.class);

        // 设置Job的partition
        job.setPartitionerClass(MyPartitioner.class);
        // 设置4个reducer，每个分区一个
        job.setNumReduceTasks(4);

        // 设置reduce相关参数
        job.setReducerClass(MyReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        // 设置作业处理完成后的输出路径
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
